import { RequestService } from './../../../service/service.service';
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';


@Component({
  selector: 'app-add-article',
  templateUrl: './add-article.component.html',
  styleUrls: ['./add-article.component.scss']
})
export class AddArticleComponent implements OnInit {
  @Input('visible') visible: Boolean
  @Output() closeAddModal = new EventEmitter<boolean>();
  @Output() refresh = new EventEmitter<boolean>();
  validateForm: FormGroup;
  textArea: Object = { minRows: 3, maxRows: 8 }
  typeList = [
    { label: '文学', value: 1 },
    { label: '科学', value: 2 },
    { label: '历史', value: 3 },
    { label: '艺术', value: 4 },
    { label: '茶余饭后', value: 5 },
    { label: '娱乐圈八卦', value: 6 }
  ]

  submitForm(): void {
    console.log(this.validateForm.valid)
    console.log(this.validateForm.value)
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.valid) {
      this.request.post('/v1/article/add', this.validateForm.value).subscribe(res => {
        console.log(res)
      })
    }
  }

  // updateConfirmValidator(): void {
  //   /** wait for refresh value */
  //   Promise.resolve().then(() => this.validateForm.controls.checkPassword.updateValueAndValidity());
  // }

  confirmationValidator = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value !== this.validateForm.controls.password.value) {
      return { confirm: true, error: true };
    }
    return {};
  };

  getCaptcha(e: MouseEvent): void {
    e.preventDefault();
  }

  constructor(private fb: FormBuilder, private request: RequestService) { }

  showModal(): void {
    this.visible = true;
  }

  handleOk(): void {
    console.log('Button ok clicked!');
  }

  handleCancel(): void {
    this.validateForm.reset()
    this.closeAddModal.emit(false)
  }

  ngOnInit() {
    this.validateForm = this.fb.group({
      title: [null, [Validators.required]],
      type: [null, [Validators.required]],
      author: [null, [Validators.required]],
      // nickname: [null, [Validators.required]],
      // phoneNumberPrefix: ['+86'],
      content: [null, [Validators.required]],
      avatar: [null, [Validators.required]],
      // captcha: [null, [Validators.required]],
      // agree: [false]
    });
  }

}
